﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PersonaLibrary.Data;

namespace PersonaLibrary.View
{
	/// <summary>
	/// Interaction logic for ConnectionTest.xaml
	/// </summary>
	public partial class ConnectionTest : Window
	{
		public ConnectionTest()
		{
			InitializeComponent();
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			Action test = delegate
			              	{
			              		using (var context = new LinqToDbDataContext())
			              		{
			              			Action<string> addServerName = x => serverName.Text = x;
			              			Dispatcher.Invoke(addServerName, context.Connection.DataSource);
			              			bool testResult = context.DatabaseExists();
			              			((App) Application.Current).ServerAvailable = testResult;
									if(!testResult)
										((App)Application.Current).Logger.Warning(string.Format("Не удалось подключиться к базе {0}", context.Connection.DataSource));
			              			TestCallback(testResult);
			              		}
			              	};

			test.BeginInvoke(null, null);
		}

		private void TestCallback(object result)
		{
			bool testResult = (bool) result;

			if (!testResult)
				MessageBox.Show("Невозможно подключиться к базе");

			Action close = Close;

			Dispatcher.BeginInvoke(close);
		}
	}
}
